package com.fzu.express.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fzu.express.entity.Type;
import com.fzu.express.mapper.TypeMapper;
import com.fzu.express.service.TypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzu.express.utils.ApiException;
import com.fzu.express.utils.PageVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tz
 * @since 2022-11-3
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService {
    @Override
    public PageVO listType(Type type, Integer pageNum, Integer pageSize) {
        // 构造分页参数
        Page<Type> pageRequest = new Page<>(pageNum, pageSize);
        // 构造条件查询器
        LambdaQueryWrapper<Type> wrapper = new LambdaQueryWrapper<>();
        // 结合实际场景，可根据type的userId，name，status，create_time,update_time查询
        // 对条件进行非空判断，不为空时添加查询条件
        // 字符串的非空判断统一使用org.apache.commons.lang3.StringUtils.isNotBlank()
        // 其他类型的非空判断统一使用 != null

        //userId
        Long userId = type.getId();
        if (userId != null){
            wrapper.eq(Type::getId, userId);
        }
        //name
        String name = type.getName();
        if (StringUtils.isNotBlank(name)){
            wrapper.eq(Type::getName, name);
        }
        //status
        Integer status = type.getStatus();
        if (status != null){
            wrapper.eq(Type::getStatus, status);
        }
        //createTime
        Date createTime = type.getCreateTime();
        if (createTime != null){
            wrapper.eq(Type::getCreateTime, createTime);
        }

        //updateTime
        Date updateTime  = type.getUpdateTime();
        if (updateTime != null){
            wrapper.eq(Type::getUpdateTime, updateTime );
        }

        //进行查询
        IPage<Type> page = super.page(pageRequest, wrapper);
        return PageVO.convert(page);
    }

    @Override
    public void addType(Type type) {
        String name = type.getName();
        LambdaQueryWrapper<Type> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Type::getName, name);
        int count = super.count(lambdaQueryWrapper);
        if (count > 0) {
            throw new ApiException("类型名称重复");
        }
        super.save(type);
    }

    @Override
    public void updateType(Type type) {
        // 更新是根据id确定记录的，所以必须对id进行非空判断
        if (type.getId() == null){
            throw new ApiException("ID值不能为空");
        }
        super.updateById(type);
    }

    @Override
    public void deleteType(Long id) {
        super.removeById(id);
    }
}
